package net.wantongtech.xa.uploadbasicinfo.service;

import com.google.common.collect.Lists;
import com.wtkj.constant.NewClearingConstant;
import com.wtkj.vo.dzzf.base.qxsjz.entity.IntegratedTransOut;
import com.wtkj.vo.dzzf.base.qxsjz.entity.PortalTransOut;
import lombok.extern.slf4j.Slf4j;
import net.wantongtech.xa.uploadbasicinfo.dao.ProcessCenterBankPayTransDataDao;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 处理部中心总对总交易扣款数据服务实现
 *
 * @author MaShibo
 * 日期 :  2020/2/6
 */
@Slf4j
@Service
public class ProcessCenterBanPayTransDataService {


    @Resource
    private ProcessCenterBankPayTransDataDao processCenterBankPayTransDataDao;

    private final TransactionTemplate transactionTemplate;

    public ProcessCenterBanPayTransDataService(PlatformTransactionManager transactionManager) {
        this.transactionTemplate = new TransactionTemplate(transactionManager);
    }

    public void process() {
        List<String> integratedIdList = processCenterBankPayTransDataDao.queryAllCenterBankPayIntegratedTransOut();
        log.info("共查询到{}个integratedId", integratedIdList.size());
        if (integratedIdList.isEmpty()) {
            return;
        }
        integratedIdList.forEach(integratedId -> {
            try {
                transactionTemplate.execute(new TransactionCallbackWithoutResult() {
                    @Override
                    protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
                        processSingle(integratedId);
                    }
                });
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        });
    }

    private void processSingle(String integratedId) {
        IntegratedTransOut ormObj = new IntegratedTransOut();
        ormObj.setIntegratedId(integratedId);
        IntegratedTransOut integratedTransOut = (IntegratedTransOut) processCenterBankPayTransDataDao.queryObject(ormObj);
        if (integratedTransOut == null) {
            log.warn("integratedId：{}，对应的数据不存在", integratedId);
            return;
        }

        Integer state = integratedTransOut.getState();
        if (state != null && state != 0) {
            log.info("integratedId：{}，发送状态：{}，错误", integratedId, state);
            return;
        }

        String signSource = integratedTransOut.getSignSource();
        if (!"4".equals(signSource)) {
            log.info("integratedId：{}，signSource：{}，错误", integratedId, signSource);
            return;
        }

        List<PortalTransOut> portalTransOutList = processCenterBankPayTransDataDao.queryPortalTransOutByIntegratedId(integratedId);
        int size = portalTransOutList.size();
        Integer count = integratedTransOut.getCount();
        if (size != count) {
            log.warn("查询到的PortalTransOut记录数：{}与合并交易中数量：{}不相等", size, count);
            return;
        }

        long totalFee = portalTransOutList.stream()
                .mapToLong(PortalTransOut::getFee)
                .sum();
        Long fee = integratedTransOut.getFee();
        if (fee != totalFee) {
            log.warn("查询到的PortalTransOut记录总金额：{}与合并交易中总金额：{}不相等", totalFee, fee);
            return;
        }

        //明细中不包含未发送的交易
        boolean noPushedTrans = portalTransOutList.stream()
                .noneMatch(portalTransOut ->
                        portalTransOut.getChannelPushState() != null && portalTransOut.getChannelPushState() == 3);
        if (noPushedTrans) {
            log.info("integratedId：{}，不包含未发送的交易明细", integratedId);
            //更新为已发送
            integratedTransOut.setState(NewClearingConstant.SendFlag.DONE);
            processCenterBankPayTransDataDao.updateObject(integratedTransOut);

        } else {
            List<PortalTransOut> pushedTransList = Lists.newArrayList();
            List<PortalTransOut> nonePushedTransList = Lists.newArrayList();

            portalTransOutList.forEach(portalTransOut -> {
                Integer channelPushState = portalTransOut.getChannelPushState();
                if (channelPushState == 3) {
                    nonePushedTransList.add(portalTransOut);
                } else if (channelPushState == 5) {
                    pushedTransList.add(portalTransOut);
                }
            });

            if (log.isInfoEnabled()) {
                List<String> nonePushedTransIdList = nonePushedTransList.stream().map(PortalTransOut::getTransactionId).collect(Collectors.toList());
                log.info("integratedId：{}，包含未发送的交易明细：{}", integratedId, nonePushedTransIdList);
            }

            int pushedCnt = pushedTransList.size();
            long pushedAmount = pushedTransList.stream().mapToLong(PortalTransOut::getFee).sum();

            log.info("integratedId：{}，已推送交易数量：{}，已推送交易总金额：{}", integratedId, pushedCnt, pushedAmount);
            ormObj.setCount(pushedCnt);
            ormObj.setFee(pushedAmount);
            ormObj.setState(NewClearingConstant.SendFlag.DONE);
            processCenterBankPayTransDataDao.updateObject(ormObj);

            nonePushedTransList.forEach(portalTransOut -> {
                String transactionId = portalTransOut.getTransactionId();
                processCenterBankPayTransDataDao.clearTransOutIntegratedInfo(transactionId);
            });


        }
    }

}
